//给你二叉树的根节点 root ，返回其节点值的 锯齿形层序遍历 。（即先从左往右，再从右往左进行下一层遍历，以此类推，层与层之间交替进行）。 
//
// 
//
// 示例 1： 
// 
// 
//输入：root = [3,9,20,null,null,15,7]
//输出：[[3],[20,9],[15,7]]
// 
//
// 示例 2： 
//
// 
//输入：root = [1]
//输出：[[1]]
// 
//
// 示例 3： 
//
// 
//输入：root = []
//输出：[]
// 
//
// 
//
// 提示： 
//
// 
// 树中节点数目在范围 [0, 2000] 内 
// -100 <= Node.val <= 100 
// 
//
// Related Topics 树 广度优先搜索 二叉树 👍 728 👎 0


package com.rising.leetcode.editor.cn;

import com.rising.leetcode.editor.cn.doc.object.TreeNode;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 二叉树的锯齿形层序遍历
 * @author rising
 * @date 2023-01-18 10:10:59
 */
 
public class P103_BinaryTreeZigzagLevelOrderTraversal {
    public static void main(String[] args) {
        Solution solution = new P103_BinaryTreeZigzagLevelOrderTraversal().new Solution();
    }

//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        Deque<TreeNode> queue1 = new LinkedBlockingDeque<>();
        Deque<TreeNode> queue2 = new LinkedBlockingDeque<>();
        queue1.add(root);
        boolean flag = true;
        List<List<Integer>> rtnList = new LinkedList<>();

        while (!queue1.isEmpty()) {
            List<Integer> temp = new LinkedList<>();
            while (!queue1.isEmpty()) {
                TreeNode first = null;
                if (flag) {
                    first = queue1.removeFirst();
                } else {
                    first = queue1.removeLast();
                }
                temp.add(first.val);
                if (first.left != null) queue2.addLast(first.left);
                if (first.right != null) queue2.addLast(first.right);
            }
            queue1.addAll(queue2);
            queue2.clear();
            rtnList.add(temp);
            flag = !flag;
        }
        return rtnList;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}
